package com.yike.order.mq;

import com.alibaba.fastjson.JSONObject;
import com.yike.order.entity.Order;
import com.yike.order.mapper.OrderMapper;
import com.yike.order.param.WxQueryRequestParam;
import com.yike.order.service.WxPayService;
import lombok.extern.java.Log;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Log
@Component
@RocketMQMessageListener(topic = "close-order-topic", consumerGroup = "close-order-group")
public class CloseOrderListener implements RocketMQListener<Long> {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WxPayService wxPayService;

    @Override
    public void onMessage(Long orderId) {
        log.info("close-order-topic 接收到消息：" + orderId);
        // 获取订单信息
        Order order = orderMapper.selectById(orderId);
        if (order != null && order.getStatus() == 0) {
            // 先去支付渠道查询一下订单状态，确认未支付则关闭订单
            WxQueryRequestParam wxQueryRequestParam = new WxQueryRequestParam();
            wxQueryRequestParam.setOutTradeNo(order.getOrderNo());
            Map<String, String> resultMap = wxPayService.orderQuery(wxQueryRequestParam);
            log.info("微信查询结果：" + JSONObject.toJSONString(resultMap));
            if ("SUCCESS".equals(resultMap.get("return_code")) && "SUCCESS".equals(resultMap.get("result_code"))
                    && "SUCCESS".equals(resultMap.get("trade_state"))) {
                // 如果已支付修改订单状态为已支付
                order.setStatus(1);
            } else {
                // 如果未支付修改订单状态为已关闭
                order.setStatus(2);
            }
            orderMapper.updateById(order);

        }

    }

}
